#include "stdafx.h"
#include "SingleLineEditWnd.h"
#include "SingleLineEditUI.h"
#include "Rect.h"

CSingleLineEditWnd::CSingleLineEditWnd(void):m_pOwner(NULL)
{
}
CSingleLineEditWnd::~CSingleLineEditWnd(void)
{

}

void CSingleLineEditWnd::Init(CSingleLineEditUI* pOwner)
{
	CStdRect rcPos = pOwner->GetPos();
	rcPos.Deflate(1, 3);
	Create(pOwner->GetManager()->GetPaintWindow(), NULL, WS_CHILD | pOwner->m_uEditStyle, 0, rcPos,(HMENU)NULL);
	SetWindowFont(m_hWnd, pOwner->GetManager()->GetThemeFont(UIFONT_NORMAL), TRUE);
	Edit_SetText(m_hWnd, pOwner->GetText());
	Edit_SetModify(m_hWnd, FALSE);
	SendMessage(EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN, MAKELPARAM(2, 2));
	Edit_SetSel(m_hWnd, 0, -1);
	Edit_Enable(m_hWnd, pOwner->IsEnabled() == true);
	Edit_SetReadOnly(m_hWnd, pOwner->IsReadOnly() == true);
	::ShowWindow(m_hWnd, SW_SHOWNOACTIVATE);
	::SetFocus(m_hWnd);
	m_pOwner = pOwner;
}

LPCTSTR CSingleLineEditWnd::GetWindowClassName() const
{
	return _T("SingleLineEditWnd");
}

LPCTSTR CSingleLineEditWnd::GetSuperClassName() const
{
	return WC_EDIT;
}

void CSingleLineEditWnd::OnFinalMessage(HWND /*hWnd*/)
{
	// Clear reference and die
	m_pOwner->m_pWindow = NULL;
	delete this;
}

LRESULT CSingleLineEditWnd::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	LRESULT lRes = 0;
	BOOL bHandled = TRUE;
	if( uMsg == WM_KILLFOCUS ) lRes = OnKillFocus(uMsg, wParam, lParam, bHandled);
	else if( uMsg == OCM_COMMAND && GET_WM_COMMAND_CMD(wParam, lParam) == EN_CHANGE ) lRes = OnEditChanged(uMsg, wParam, lParam, bHandled);
	else bHandled = FALSE;
	if( !bHandled ) return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
	return lRes;
}

LRESULT CSingleLineEditWnd::OnKillFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	LRESULT lRes = ::DefWindowProc(m_hWnd, uMsg, wParam, lParam);
	PostMessage(WM_CLOSE);
	return lRes;
}

LRESULT CSingleLineEditWnd::OnEditChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	if( m_pOwner == NULL ) return 0;
	// Copy text back
	int cchLen = ::GetWindowTextLength(m_hWnd) + 1;
	LPTSTR pstr = static_cast<LPTSTR>(_alloca(cchLen * sizeof(TCHAR)));
	ASSERT(pstr);
	if( pstr == NULL ) return 0;
	::GetWindowText(m_hWnd, pstr, cchLen);
	m_pOwner->SetText(pstr);
	return 0;
}